package edu.clarkson.ee368.spring2012.coreservices;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import javax.inject.Inject;
import javax.xml.ws.ProtocolException;

public class AndroidDeviceNotifier implements DeviceNotifier {

	private static final String SERVICE = "ac2dm";
	private static URL C2DM_SERVICE_URL = null;
	static {
		try {
			C2DM_SERVICE_URL = new URL(
					"https://android.apis.google.com/c2dm/send");
		} catch (MalformedURLException e) {
			C2DM_SERVICE_URL = null;
			e.printStackTrace();
		}
	}
	// Required parameters for C2DM
	private static final String REGISTRATION_ID = "registration_id";
	private static final String COLLAPSE_KEY = "collapse_key";

	@Inject
	@ClientLogin
	private GoogleServiceAuthenticator authenticator;

	@Override
	public void sendMessage(HostedApplication hostedApplication, Device device,
			Map<String, String> data) throws GoogleServiceAuthenticationException {

		// TODO need to send a better value for "collapse_key"

		byte[] postData = buildC2DMPostData(device, data);

	//	try {
			HttpURLConnection connection = createC2DMConnection();
			authenticator.applyAuthenticationToHttpConnection(
					hostedApplication, SERVICE, connection);
			writeDataToConnection(postData, connection);

			authenticator.ensureAuthenticationWasAccepted(connection);
			
			
//		

//		} catch (Exception e) {
//			e.printStackTrace();
//		}

	}

	private void writeDataToConnection(byte[] postData,
			HttpURLConnection connection) {
		try {
			connection.setRequestProperty("Content-Length",
					Integer.toString(postData.length));
			OutputStream os = connection.getOutputStream();
			os.write(postData);
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private HttpURLConnection createC2DMConnection() {
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) C2DM_SERVICE_URL.openConnection();
			connection.setRequestMethod("POST");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		}
		connection.setUseCaches(false);
		connection.setDoOutput(true);

		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		return connection;
	}

	private byte[] buildC2DMPostData(Device device, Map<String, String> data) {
		StringBuilder builder = new StringBuilder();
		builder.append(REGISTRATION_ID + "=").append(device.getC2DMRegistrationId());
		builder.append("&" + COLLAPSE_KEY + "=").append("arbitrary");
		for (Entry<String, String> entry : data.entrySet()) {
			builder.append("&data." + entry.getKey() + "=").append(
					entry.getValue());
		}
		return builder.toString().getBytes();
	}

}
